# coding: utf-8
import json, re
import glob
import os, sys, rarfile
from tqdm import tqdm
from typing import Dict, Any
from pathlib import Path
import time

import platform
import jaydebeapi
import jpype
import jpype.imports
from jpype.types import *
import subprocess
import pyodbc, io

import numpy as np
import pandas as pd

import warnings, logging

warnings.filterwarnings("ignore")
# 配置日志
from utils.logging_config import setup_logger
logger = setup_logger('File Unrar')


# rar文件解压
def unrar_accdb_file(source_rar, target_path):
    # 设置unrar路径（Ubuntu中通常自动检测，但可显式设置）
    rarfile.UNRAR_TOOL = "/usr/bin/unrar"  # Ubuntu默认路径
    
    try:
        # 打开RAR文件
        with rarfile.RarFile(source_rar) as rf:
            logger.info("RAR文件内容:")
            logger.info(rf.namelist())  # 打印文件列表
            
            # 解压所有文件到指定目录
            rf.extractall(path=target_path)
            logger.info(f"成功解压到: {target_path}")
            
            # 访问解压后的文件示例
            extracted_file = os.path.join(target_path, rf.namelist()[0])
            logger.info(f"第一个文件路径: {extracted_file}")
        return
    
    except rarfile.RarCannotExec as e:
        logger.info("错误: 未找到unrar工具。请确保已安装:", e)
        logger.info("尝试运行: sudo apt install unrar")
    except rarfile.BadRarFile as e:
        logger.info("错误: 文件损坏或格式不支持:", e)
    except rarfile.PasswordRequired as e:
        logger.info("错误: 需要密码:", e)
        # 处理带密码的文件
        # with rarfile.RarFile(source_rar, pwd='yourpassword') as rf:
        #    rf.extractall(target_path)
    except Exception as e:
        logger.info("未知错误:", e)

def extract_rar_batch(file_paths, source_str='2025年1-3月汇总', replace_str='20251t3_unrar'):
    """ 批量提取rar, 入参为文件列表 """
    start=time.time()
    for fpth in tqdm(file_paths):
        print(fpth)
        rar_path = fpth
        extract_dir = Path('/'.join(str(fpth).split('/')[0:-1]).replace(source_str, replace_str))
        # 确保解压目录存在
        os.makedirs(extract_dir, exist_ok=True)
        unrar_accdb_file(rar_path, extract_dir)
    end=time.time()
    logger.info(f'This step takes {round(end-start)} seconds')
    return


def get_dir_files(root_dir):
    """遍历目录树， 获取子目录列表和文件列表"""
    dir_paths = []
    file_paths = []
    for path in root_dir.rglob('*'):  # 使用rglob可以递归地匹配所有子目录和文件
        if path.is_dir():
            dir_paths.append(path)
            # print(f'Directory: {path}')
        else:
            file_paths.append(path)
            # print(f'File: {path}')
    return dir_paths, file_paths








